import apis from "../services/publicApi";

export default {
  namespace: "user",
  state: {
    userInfo: {},
    collapsed: false,
    department: undefined,
    menuData: [],
    btnAuthority: [],
    tenantList: []
  },
  effects: {
    // 用户信息
    *getUserInfo(action, { call, put }) {
      const res = yield call(apis.getUserInfo);
      const { datas: userInfo = {} } = res || {};
      const tenantRes = yield call(apis.getTenantList, userInfo.userId);
      const { datas: tenantList = [] } = tenantRes || {};
      // 适配后端参数，租户code以数组的方式传入
      const tenantsTemp = tenantList.map(t => ({
        ...t,
        tenantCode: [t.tenantCode]
      }));
      yield put({
        type: "updateState",
        payload: {
          department: userInfo.department,
          userInfo,
          tenantList:
            tenantsTemp.length > 0
              ? [
                  ...tenantsTemp,
                  {
                    ...tenantsTemp[0],
                    id: "100000",
                    tenantCode: tenantList.map(t => t.tenantCode),
                    tenantName: "全部"
                  }
                ]
              : []
        }
      });
    },
    // 退出登陆
    *logout(action, { call }) {
      const { data } = yield call(apis.logout);
      if (data && data.logoutUrl) {
        window.location.href = data.logoutUrl;
      }
    },
    *saveCollapse({ payload }, { put }) {
      yield put({ type: "put/putcollap", payload });
    },

    *getMenu(_, { call, put }) {
      const res = yield call(apis.getMenu);
      const { datas: { menu, btn = [] } = {} } = res || {};
      yield put({
        type: "updateState",
        payload: { menuData: menu, btnAuthority: btn }
      });
    }
  },
  reducers: {
    "put/putcollap": (state, { payload }) => ({
      ...state,
      collapsed: payload
    }),
    updateState: (state, { payload }) => ({
      ...state,
      ...payload
    })
  }
};
